import { Cascader, Col, Spin, Table, Tabs } from 'antd'
import Filter from '@/components/filter'
import React, { useEffect, useMemo, useState } from 'react'
import http from '@/utils/request'
import type { DictItem, optionConfigType } from '@/types'
import { orderListcolumns } from '@/pages/order/model'
import { useLocation } from 'react-router-dom'
import './index.scss'
import useChinaAreasStore from '@/store/chinaAreas'

interface filteType {
  [key: string]: any,
  provinceCode?: string,
  cityCode?: string,
  areaCode?: string,
  bizTeamId?: string,
  seatTeamId?: string,
  bizTypeId?: string,
  comboId?: string,
  endTime?: string,
  startTime?: string,
  timeRange?: string
}

const initfilter: filteType = {
  provinceCode: undefined,
  cityCode: undefined,
  areaCode: undefined,
  bizTeamId: undefined,
  bizTypeId: undefined,
  comboId: undefined,
  endTime: undefined,
  seatTeamId: undefined,
  startTime: undefined
}
let filterData: filteType = {
  ...initfilter
}

const Analysis: React.FC = () => {
  const location = useLocation()
  const pathname = useMemo(() => {
    return location.pathname
  }, [location])

  const [loading, setLoading] = useState(true)

  const [optionConfig, setOptionConfig] = useState<optionConfigType>({
    bizTeams: [],
    seatTeams: [],
    bizTypes: [],
    comboIds: [],
    gifts: []
  })
  const setOptionByKey = (key: string, val: DictItem[]) => {
    setOptionConfig((optionConfig) => ({
      ...optionConfig,
      [key]: val
    }))
  }
  const operateDataList = () => {
    return [
      {
        label: '业务团队',
        labelKey: 'teamName',
        url: '/disp/biz/team/page',
        dictName: 'bizTeams',
        params: {
          teamType: 'Biz'
        }
      },
      {
        label: '坐席团队',
        labelKey: 'teamName',
        url: '/disp/biz/team/page',
        dictName: 'seatTeams',
        params: {
          teamType: 'Seats'
        }
      },
      {
        label: '业务类型',
        labelKey: 'name',
        url: '/disp/biz/operation/pageBizType',
        dictName: 'bizTypes'
      },
      {
        label: '套餐',
        labelKey: 'name',
        url: '/disp/biz/operation/pageCombo',
        dictName: 'comboIds'
      },
      {
        label: '礼品',
        labelKey: 'name',
        url: '/disp/biz/operation/pageGift',
        dictName: 'gifts'
      }
    ].map(requestItem => {
      return http.post(requestItem.url, {
        ...(requestItem.params || {}),
        pageNum: 1,
        pageSize: 99999,
        status: 'Enable'
      }).then(res => {
        const options = (res?.data?.list || []).map((item: { [requestItem.labelKey]: string, id: string }) => {
          return {
            value: item.id,
            label: item[requestItem.labelKey],
            disabled: item.status !== 'Enable',
            teamType: item.teamType || ''
          }
        })
        setOptionByKey(requestItem.dictName, options)
      })
    })
  }

  useEffect(() => {
    operateDataList()
  }, [])

  const [queryType, setQueryType] = useState<string>('Biz')

  const filterItems = useMemo(() => {
    const teamList = queryType === 'Biz' ? [
      {
        type: 'select',
        key: 'bizTeamId',
        label: '业务团队',
        options: optionConfig.bizTeams
      }
    ] : [
      {
        type: 'select',
        key: 'seatTeamId',
        label: '坐席团队',
        options: optionConfig.seatTeams
      }
    ]
    return [
      ...teamList,
      {
        type: 'input',
        key: 'seatUsername',
        label: '坐席人员',
        placeholder: '请输入人员姓名'
      },
      {
        type: 'input',
        key: 'bizTeamUsername',
        label: '业务人员',
        placeholder: '请输入人员姓名'
      },
      {
        type: 'select',
        key: 'bizTypeId',
        label: '业务类型',
        options: optionConfig.bizTypes
      }, {
        type: 'select',
        key: 'comboId',
        label: '套餐',
        options: optionConfig.comboIds
      }, {
        type: 'RangePicker',
        key: 'timeRange',
        label: '时间范围'
      }]
  }, [optionConfig, queryType])

  const [pageConfig, setPageConfig]= useState({
    pageNum: 1,
    pageSize: 10,
    total: 0,
    current: 1
  })

  const filterChange = (val: any, key: keyof filteType) => {
    if (key === 'timeRange') {
      filterData.startTime = val ? val[0].format('YYYY-MM-DD HH:mm:ss') : ''
      filterData.endTime = val ? val[1].format('YYYY-MM-DD HH:mm:ss') : ''
    } else {
      filterData[key] = val
    }
  }
  const [result, setResult] = useState({
    successNum: 0,
    successRate: 0,
    totalNum: 0
  })
  pageConfig.pageNum = 1

  const [dataSource, setDataSource] = useState<any[]>([])

  const queryData = async () => {
    setLoading(true)
    const resCount = await http.post('/disp/biz/analysis/countDataStatisticsForPc', {
      ...filterData,
      queryType
    })
    setResult(resCount.data)
    queryPageList()
    setLoading(false)
  }

  useEffect(() => {
    queryData()
  }, [])
  
  const queryPageList = async () => {
    setLoading(true)
    const orderList = await http.post('/disp/biz/analysis/pageDataStatisticsOrderForPc', {
      ...filterData,
      queryType,
      pageNum: pageConfig.pageNum,
      pageSize: pageConfig.pageSize
    })
    setLoading(false)
    setPageConfig(config => {
      return {
        ...config,
        total: orderList.data.total
      }
    })
    setDataSource(orderList.data.list || [])
  }

  const tabs = [{
    key: 'Biz',
    label: '业务'
  }, {
    key: 'Seats',
    label: '坐席'
  }]

  const tabChange = (val: string) => {
    filterData = { ...initfilter }
    setPageConfig({
      pageNum: 1,
      pageSize: 10,
      total: 0,
      current: 1
    })
    setQueryType(val)
    queryData()
  }

  const addressChange = (selected: number[]) => {
    setPageConfig((config) => {
      return {
        ...config,
        pageNum: 1
      }
    })
    const keys = ['provinceCode', 'cityCode', 'areaCode']
    if (selected) {
      selected.forEach((value, index) => {
        filterData[keys[index]] = value
      })
    } else {
      keys.forEach(key => {
        filterData[key] = undefined
      })
    }
  }
  
  const pageChange = (pageNum: number, pageSize: number) => {
    pageConfig.pageSize = pageSize
    pageConfig.pageNum = pageNum
    pageConfig.current = pageNum
    queryPageList()
  }

  const { chinaAreas } = useChinaAreasStore()
  const filter = (inputValue: string, path: any[]) =>
    path.some(
      (option) => (option.name as string).toLowerCase().indexOf(inputValue.toLowerCase()) > -1
    )

  return (
    <div className="page">
      <Tabs defaultActiveKey={queryType} items={tabs} onChange={tabChange}/>
      <Spin spinning={loading}>
        <Filter
          prefix={(<Col className="filter-item" xs={24} md={12} lg={8} xl={6}>
            <div className="label">区域：</div>
            <Cascader
              key={queryType}
              options={chinaAreas}
              onChange={addressChange}
              fieldNames={{
                label: 'name',
                value: 'region',
                children: 'childRegion'
              }}
              placeholder="请选择省市区"
              changeOnSelect
              showSearch={{ filter }}
              style={{ width: '100%' }}
            />
          </Col>)}
          items={filterItems}
          onChange={filterChange}
          onSure={queryData}/>
        <div className="count-wrapper flex-row flex-item">
          <div className="count-item flex1 flex-row flex-item">
            <div className="name flex1">成功数量</div>
            <div className="val">{result.successNum}</div>
          </div>
          <div className="gap"/>
          <div className="count-item flex1 flex-row flex-item">
            <div className="name flex1">总数量</div>
            <div className="val">{result.totalNum}</div>
          </div>
          <div className="gap"/>
          <div className="count-item flex1 flex-row flex-item">
            <div className="name flex1">成功率</div>
            <div className="val">{result.successRate}</div>
          </div>
        </div>
        <Table
          pagination={{ 
            position: ['bottomRight'], 
            ...pageConfig, 
            onChange: pageChange, 
            showTotal: (total) => `共 ${total} 条`,
            pageSizeOptions: ['10', '20', '30', '50'],
            showSizeChanger: true
          }}
          dataSource={dataSource}
          scroll={{ x: 'max-content' }}
          columns={orderListcolumns(pathname)}
          rowKey="id" />
      </Spin>
    </div>
  )
}
export default Analysis